import os
import django
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
django.setup()


import traceback
import json
import logging
from rest_framework import request
from extensions.common.base import *
from extensions.my_queue import MessageQueue
from extensions.en_wechat import WechatPy, ParseData

logger = logging.getLogger("django")


# def save(data):
    # 从 XML 中获取审批编号
    # template_id = data['xml']['approvalinfo']['templateid']
    # w = WechatPy(user.team)
    # dic = {}
    # # 创建树
    # dic['template_data'] = w.create_templatetree(template_id)
    #
    # # 创建审批流程
    # spno = data['xml']['approvalinfo']['spno']
    #
    # dic['approval_data'] = w.create_approval_process(spno, template_id)

    # try:
    #     template_obj = ApprovalTemplate.objects.get(template_id=template_id)
    # except ApprovalTemplate.DoesNotExist:
    #     return False
    #
    # if not template_obj.approvaltype:
    #     return False
    #
    # tree_all = ApprovalTemplateTree.objects.filter(tree_id=template_obj.template.tree_id)

    # 检查是否存在 to_type_id 为空的情况
    # if tree_all.filter(to_type__isnull=True).exists():
    #     return False

    # 匹配产品数量关系
    # data = dic['approval_data']
    #
    #
    # request.user = user
    # parseData = ParseData(data, request, template_obj)
    # parseData.save_data()
    #



def callback(ch, method, properties, body):
    try:
        data = json.loads(body)
        logger.info(f"handler callback: {data}")
        save(data)
    except Exception as e:
        logger.info(body)
        logger.error(traceback.format_exc())


if __name__ == '__main__':
    queue = MessageQueue(Event_MQ, RABBITMQ)
    connection = pika.BlockingConnection(queue.get_queue_parameter())
    channel = connection.channel()
    channel.exchange_declare(exchange=queue.exchange,
                             exchange_type=queue.exchange_type,
                             arguments=queue.arguments)
    channel.queue_declare(queue=queue.queue, durable=True)
    channel.queue_bind(queue=queue.queue,
                       exchange=queue.exchange,
                       routing_key=queue.routing_key)

    channel.basic_consume(queue=queue.queue, on_message_callback=callback, auto_ack=True)

    print('Waiting for messages...')
    logger.info('Waiting for messages...')
    channel.start_consuming()

    connection.close()
